<template>
  <div>
    <!-- 搜索栏 -->
    <form action="/">
      <van-search
      background="#3296fa"
      v-model="searchText"
      placeholder="请输入搜索关键词"
      show-action
      @search="onSearch(searchText)"
      @focus="isResultShow=false">
      <template #action>
        <div @click="$router.back()" style="color:#fff;">取消</div>
      </template>
      </van-search>
    </form>
    <!-- 搜索结果 -->
    <search-result
    v-if="isResultShow"
    :search-text="searchText"
    />
    <!-- 联想建议 -->
    <search-suggestion
    v-else-if="searchText"
    :search-text="searchText"
    @search="onSearch"/>
    <!-- 历史记录 -->
    <search-history
    v-else
    :search-histories="searchHistories"
    @search="onSearch"
    @update-histories="searchHistories = $event" />

  </div>
</template>

<script>
import SearchSuggestion from './components/search-suggestion'
import SearchHistory from './components/search-history'
import SearchResult from './components/search-result'
import { setItem, getItem } from '@/utils/storage'
// import { getUserSearchHistories } from '@/api/search'
import { mapState } from 'vuex'

export default {
  name: 'SearchIndex',
  components: {
    SearchSuggestion,
    SearchHistory,
    SearchResult
  },
  data () {
    return {
      searchText: '',
      isResultShow: false,
      searchHistories: []
    }
  },
  async created () {
    this.loadSearchHistories()
  },
  watch: {
    // 监视搜索历史记录的变化 存储到本地存储
    searchHistories () {
      setItem('search-histories', this.searchHistories)
    }
  },
  computed: {
    ...mapState(['user'])
  },
  methods: {
    onSearch (searchText) {
      this.searchText = searchText
      const index = this.searchHistories.indexOf(searchText)
      if (index !== -1) {
        // 重复的删除
        this.searchHistories.splice(index, 1)
      }
      // 最新的放到顶部
      this.searchHistories.unshift(searchText)

      // 登录了 存储到线上
      // 没有登录 存储到本地
      // setItem('search-histories', this.searchHistories)

      // 展示搜索结果
      this.isResultShow = true
    },
    async loadSearchHistories () {
      const searchHistories = getItem('search-histories') || []
      // if (this.user) {
      //   const { data } = await getUserSearchHistories()
      //   searchHistories = [...new Set([
      //     ...searchHistories,
      //     ...data.data.keywords
      //   ])]
      // }
      this.searchHistories = searchHistories
    }
  }
}
</script>

<style lang="less" scoped>

</style>
